<?php
/**
 * 地区管理控制器
 * ===============================================
 * @copyright 深圳市顶速网络科技有限公司  http://fasttop.top
 * ===============================================
 * @author: Ketity <970564173@qq.com>
 * @date: 2015-5-19
 */
namespace Admin\Controller;
class AreaController extends BaseController {
	
	/**
	 * 初始化
	 * @see Common\Controller.AdminBaseController::_initialize()
	 */
	public function _initialize() {
		parent::_initialize ();
	}
	
	/**
	 * 地区列表
	 */
	public function index() {
		$requestdata = I ( 'request.' );
		$parentid = empty ( $requestdata ['parentid'] ) ? 0 : $requestdata ['parentid'];
		$where ['parentid'] = $parentid;
		$areas = D ( 'Area' )->find ( $parentid );
		if ($parentid == 0) {
			$region_type = 0; //国家级
		} else {
			$region_type = $areas ['region_type'] + 1;
		}
		switch ($region_type) {
			case 0 :
				$areaInfo = L ( 'text_area_country' );
				$addInfo = L ( 'text_area_addcountry' );
				break;
			case 1 :
				$areaInfo = L ( 'text_area_province' );
				$addInfo = L ( 'text_area_addprovince' );
				break;
			case 2 :
				$areaInfo = L ( 'text_area_city' );
				$addInfo = L ( 'text_area_addcity' );
				break;
			case 3 :
				$areaInfo = L ( 'text_area_cantonal' );
				$addInfo = L ( 'text_area_ddcantonal' );
				break;
			default :
				break;
		}
		$arealist = D ( 'Area' )->getList ( $where );
		$this->assign ( 'list', $arealist );
		$this->assign ( 'areaInfo', $areaInfo );
		$this->assign ( 'addInfo', $addInfo );
		$this->assign ( 'region_name', $areas ['region_name'] );
		$this->assign ( 'region_type', $region_type );
		$this->assign ( 'parentid', $parentid );
		$this->display ();
	}
	
	/**
	 * 更新地区名称
	 */
	public function editArea() {
		$postdata = I ( 'post.' );
		if (empty ( $postdata ['region_name'] ) || empty ( $postdata ['id'] )) {
			$return = array ('info' => L ( 'error_id_regionname_empty' ) );
			echo json_encode ( $return );
			exit ();
		}
		//判断同级下是否有重复的地区名称
		$parentid = D ( 'Area' )->getParentById ( $postdata ['id'] );
		$names = D ( 'Area' )->getNameByPid ( $parentid );
		if (in_array ( $postdata ['region_name'], $names )) {
			$return = array ('info' => L ( 'error_regionname_exists' ) );
			echo json_encode ( $return );
			exit ();
		}
		if (false === D ( 'Area' )->editArea ( $postdata ['id'], array ('region_name' => $postdata ['region_name'] ) )) {
			$return = array ('info' => D ( 'Area' )->getError () );
		} else {
			$return = array ('info' => L ( 'success_edit' ) );
		}
		echo json_encode ( $return );
		exit ();
	}
}